<template>
  <el-dialog title="维护管理员" :visible.sync="open" width="1000px" append-to-body :close-on-click-modal="false">
    <div>

      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px" label-suffix="：">
        <el-form-item label="登录名" prop="userName">
          <el-input v-model="queryParams.userName" placeholder="请输入登录名" clearable style="width: 200px" @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 200px" @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="userList" border>
        <el-table-column label="编号" align="center" key="userId" prop="userId" width="80"/>
        <el-table-column label="登录名" align="center" key="userName" prop="userName" :show-overflow-tooltip="true"/>
        <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true"/>
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120"/>
        <el-table-column label="状态" align="center" key="status">
          <template slot-scope="scope">
            {{ scope.row.status === '0' ? '正常' : '停用' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

      <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" :visible.sync="editOpen" width="700px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-suffix="：">
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户昵称" prop="nickName">
                <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item v-if="form.userId == undefined" label="登录名" prop="userName">
                <el-input v-model="form.userName" placeholder="请输入登录名" maxlength="30"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
                <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户性别">
                <el-select v-model="form.sex" placeholder="请选择性别">
                  <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>

    </div>
  </el-dialog>
</template>

<script>
import {getUser, listUser, resetUserPwd, updateUser} from "@/api/train/training/user";

export default {
  name: "RegulatoryAdmin",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  data() {
    return {
      open: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      editOpen: false,
      // 默认密码
      initPassword: undefined,
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        trainingSchoolId: undefined,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        pageNum: 1,
        pageSize: 10,
      },
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "登录名不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '登录名长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: "用户昵称不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "用户密码不能为空", trigger: "blur"},
          {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'},
          {pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur"}
        ],
        email: [{type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}],
        phonenumber: [{pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}]
      }
    };
  },
  methods: {
    openAdmin(trainingSchoolId) {
      this.open = true

      this.queryParams.trainingSchoolId = trainingSchoolId
      this.$nextTick(() => {
        this.getList();
        this.getConfigKey("sys.user.initPassword").then(response => {
          this.initPassword = response.msg;
        });
      });
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;

      listUser(this.queryParams).then(response => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.editOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        trainingSchoolId: undefined,
        userId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId || this.ids;
      getUser(userId).then(response => {
        this.form = response.data;
        this.editOpen = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({value}) => {
        resetUserPwd(row.userId, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateUser(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.editOpen = false;
            this.getList();
          });
        }
      });
    },
  }
};
</script>
